// 政采云区块链存证服务
'use strict';

const Service = require('egg').Service;
const { createHash } = require('crypto');

class BlockchainService extends Service {
  async record(payload) {
    const { ctx } = this;
    const timestamp = Date.now();
    
    // 生成符合GM/T 0003标准的哈希
    const hash = createHash('sm3')
      .update(JSON.stringify(payload))
      .digest('hex');

    // 调用政采云区块链存证接口
    const result = await ctx.curl(`${ctx.app.config.zcy.blockchain}/api/v1/record`, {
      method: 'POST',
      headers: {
        'X-Gov-Signature': this._generateSignature(payload)
      },
      data: {
        chainId: 'ZCY_ERP_CHAIN',
        dataHash: hash,
        timestamp,
        metaData: {
          provinceCode: ctx.state.user.provinceCode,
          operator: ctx.user.id
        }
      }
    });

    // 记录本地存证日志
    await ctx.model.Blockchain.create({
      tx_hash: result.data.txHash,
      data_hash: hash,
      operation_type: payload.action,
      created_by: ctx.user.id
    });

    return result.data;
  }

  _generateSignature(payload) {
    // 实现国密SM2签名算法
  }
}

module.exports = BlockchainService;